package org.javacore.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author liufan
 * @version 1.0
 * @date 2023/3/2 17:12
 */
public class SemaphoreDemo2 {

    private final static int threadCount = 20;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire(2);//一开始就申请获取全部许可，退化成穿行执行
                    System.out.println(threadNum + Thread.currentThread().getName() + "获取了许可");
                    Thread.sleep(1000);
                    System.out.println(threadNum + Thread.currentThread().getName() + "释放了许可");
                    semaphore.release(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();


    }
}
